﻿using System;
using System.Globalization;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

namespace Wild2.Models.Auth
{
    public class UserIP
    {
        public static void UserIPLog(Int32 userId)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO [UserIP]([ID_User], [IP], [XIP], [Date], [UserAgent]) VALUES(@UID, @IP, @XIP, GETDATE(), @UA)", conn))
                {
                    cmd.Parameters.Add("@UID", System.Data.SqlDbType.Int).Value = userId;
                    cmd.Parameters.Add("@IP", System.Data.SqlDbType.NVarChar, 20).Value = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) cmd.Parameters.Add("@XIP", System.Data.SqlDbType.NVarChar, 20).Value = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    else cmd.Parameters.Add("@XIP", System.Data.SqlDbType.NVarChar, 20).Value = DBNull.Value;
                    if (HttpContext.Current.Request.UserAgent != null) cmd.Parameters.Add("@UA", System.Data.SqlDbType.NVarChar, 200).Value = HttpContext.Current.Request.UserAgent.ToString(CultureInfo.InvariantCulture);
                    else cmd.Parameters.Add("@UA", System.Data.SqlDbType.NVarChar, 200).Value = DBNull.Value;
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
            }
        }
    }
}